﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Common
{
    /// <summary>
    /// 线程信号量管理器
    /// </summary>
    public class ThreadSignalManager
    {
        /// <summary>
        /// 私有化构造器，禁止直接初始化本类。构造实例需调用Singleton("")方法
        /// </summary>
        private ThreadSignalManager() { }
        private ManualResetEvent _resetEvent = new ManualResetEvent(false);
        private readonly static ConcurrentDictionary<string, ThreadSignalManager> dictionary = new ConcurrentDictionary<string, ThreadSignalManager>();
        /// <summary>
        /// 线程信号量管理器
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static ThreadSignalManager Singleton(string name)
        {
            return dictionary.GetOrAdd(name, (v) =>
            {
                return new ThreadSignalManager();
            });
        }
        /// <summary>
        /// 等待信号量通知
        /// </summary>
        /// <param name="seconds"></param>
        public void WaitOne(int? seconds)
        {
            _resetEvent.Reset();
            if (seconds.HasValue)
            {
                _resetEvent.WaitOne(seconds.Value * 1000);
            }
            else
            {
                _resetEvent.WaitOne();
            }
        }
        /// <summary>
        /// 发送信号量
        /// </summary>
        public void Set()
        {
            _resetEvent.Set();
        }
        /// <summary>
        /// 重置信号量管理器
        /// </summary>
        public void Reset()
        {
            _resetEvent.Reset();
        }
    }
}
